/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.RequestContext;
import com.downlove.database.QueryHelper;
import com.zito.ErrMsgException;
import com.zito.bean.Article;
import com.zito.bean.Articlefiles;
import com.zito.bean.Articlephotos;
import com.zito.bean.Columnz;
import com.zito.common.Paginator;

/**
 * @author YunHai-Home
 * 
 */
public class ArticleManager {

	private Paginator paginator;
	private Article article = new Article();
	private final Logger logger = LoggerFactory
			.getLogger(ArticleManager.class);

	/**
	 * 分页
	 * @return
	 */
	public String getPaginator() {
		return this.paginator.getCssPageBlock();
	}

	public Paginator getPaginatorBean() {
		return this.paginator;
	}
	
	//**************************** 查询类方法 START ******************************//
	
	/**
	 * 根据栏目ID查询文章列表
	 * @param pagesize
	 * @return
	 */
	public List<Article> getArticleListByCol(Long columnid, int pagesize) {
		String filter = " 1=1 ";
		if (columnid != -1L) {
			Columnz column = new Columnz().Get(columnid);//获取对象
			if (column == null || column.getType() == 0) {//对象为空，或判断type属性
				filter += " AND columnid = " + columnid;
			} else {
				filter += " AND specialid = " + columnid;
			}
		}
		return articleListByCol(filter, "", pagesize);
	}
	
	/**
	 * 根据栏目ID查询文章列表
	 * @param pagesize
	 * @return
	 */
	public List<Article> getArticleListBySearch(String key, int pagesize) {
		String filter = " 1=1 ";
		return articleListByCol(filter, key, pagesize);
	}
	
	/**
	 * 根据栏目ID查询文章列表(管理后台使用，只查询管理员发布的文章)
	 * @param pagesize
	 * @return
	 */
	public List<Article> articleList(int pagesize) {
		RequestContext rc = RequestContext.get();
		Long columnid = rc.param("columnid", -1L);
		String searchkey = rc.param("searchkey", "");
		String filter = " `type` = 0 AND columnid NOT IN (SELECT ID FROM columnz WHERE function <>0) ";
		if (columnid != -1L) {
			Columnz column = new Columnz().Get(columnid);//获取对象
			if (column == null || column.getType() == 0) {//对象为空，或判断type属性
				filter += " AND columnid = " + columnid;
			} else {
				filter += " AND specialid = " + columnid;
			}
		}
		return articleListByCol(filter, searchkey, pagesize);
	}

	/**
	 * 根据栏目ID查询文章列表
	 * @param columnid
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Article> articleListByCol(String filter,String searchKey, int pagesize) {
		RequestContext rc = RequestContext.get();
		Article article = new Article();
		if(searchKey.length()>0){
			filter+=" AND (title like '%"+searchKey+"%') ";
		}
		int total = article.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = article.idListFilter(filter, curpage, pagesize);
		return article.LoadList(tmpList);
	}
	
	/**
	 * 查询首页面头条图片新闻
	 * @param columnid
	 * @param pagesize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Article> getTopphotoArticleList(int pagesize) {
		Article article = new Article();
		String sql ="SELECT ID FROM article WHERE isphoto = 1 AND mainphoto IS NOT NULL " +
				" ORDER BY topic DESC,postdate DESC LIMIT ?";
		List<Long> tmpList = QueryHelper.queryList(sql, pagesize);
		return article.LoadList(tmpList);
	}


	/**
	 * 查询上一篇
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Article getLastArticle(Long columnid,Long articleid,String postdate) throws Exception{
		String sql ="SELECT * FROM article WHERE columnid = ? AND postdate>=? AND ID != ? ORDER BY topic DESC,postdate Limit 1";
		Article obj = new Article();
		obj = QueryHelper.read(Article.class, sql, columnid,postdate,articleid);
		return obj;
	}
	

	/**
	 * 查询下一篇 
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Article getNextArticle(Long columnid,Long articleid,String postdate) throws Exception{
		String sql ="SELECT * FROM article WHERE columnid = ? AND postdate<=? AND ID != ? ORDER BY topic DESC,postdate DESC Limit 1";
		Article obj = new Article();
		obj = QueryHelper.read(Article.class, sql, columnid,postdate,articleid);
		return obj;
	}

	/**
	 * 查询文章附件
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<Articlefiles> getArticlefilesByActid(Long articleid){
		Articlefiles obj = new Articlefiles();
		String sql = "SELECT id FROM Articlefiles WHERE articleid="+articleid+"  ORDER BY id";
		List<Long> tmpList = QueryHelper.queryList(sql);
		return obj.LoadList(tmpList);
	}
	//**************************** 查询类方法 END ******************************//
	/**
	 * 更新点击次数
	 * @return
	 */
	public boolean UpdateView(Long articleid) throws Exception{
		boolean re = false;
		String sql ="UPDATE article SET view = view+1 WHERE ID = ?";
		re = QueryHelper.update(sql, articleid)>0;
		return re;
	}
	
	/**
	 * 保存文章
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean operatingPost() throws ErrMsgException, IOException {
		RequestContext rc = RequestContext.get();
		long tempid = rc.param("id", -1);
		return tempid == -1 ? insertArticle(rc) : editArticle(rc);
	}

	/**
	 * 新增文章
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean insertArticle(RequestContext rc)
			throws ErrMsgException, IOException {
		Article article = new Article();
		article = rc.form(Article.class);
		String error = article.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		article.setType(0);
		article.setScore(0);
		article.setStatus(-1);
		article.setAuthorid(MasterSession.get().getUserID());
		article.setAuthor(MasterSession.get().getUserName());
		article.setIsphoto(StringUtils.isBlank(article.getMainphoto()) ? 0 : 1);
		return article.Save(RequestContext.get().session().getId()) != -1L;
	}

	/**
	 * 编辑文章
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean editArticle(RequestContext rc)
			throws ErrMsgException, IOException {
		Article article = new Article();
		article = rc.form(Article.class);
		if (article.getId() == -1)
			return false;
		String error = article.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		article.setIsphoto(StringUtils.isBlank(article.getMainphoto()) ? 0 : 1);
		return article.Update(RequestContext.get().session().getId(),
				"columnid", "specialid", "title", "content", "isphoto", "postdate", "mainphoto", "id") != -1L;
	}

	/**
	 * 获取文章详细
	 * @return
	 */
	public Article getArticle() {
		RequestContext rc = RequestContext.get();
		long id = rc.param("id", -1);
		if (id == -1)
			return article;
		return article.Get(id);

	}

	/**
	 * 设置置顶
	 * @return
	 */
	public boolean setTopic() {
		RequestContext rc = RequestContext.get();
		long id = rc.param("id", -1);
		if (id == -1)
			return false;
		article = new Article();
		article.setId(id);
		return article.setTopic() == 1 ? true : false;
	}

	/**
	 * 取消置顶
	 * @return
	 */
	public boolean unTopic() {
		RequestContext rc = RequestContext.get();
		long id = rc.param("id", -1);
		if (id == -1)
			return false;
		article = new Article();
		article.setId(id);
		return article.unTopic() == 1 ? true : false;
	}

	/**
	 * 删除文章
	 * @return
	 * @throws ErrMsgException
	 */
	public boolean deleteArticle() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		Article article = new Article();
		ArticlephotosManager photo = new ArticlephotosManager();
		ArticlefilesManager file = new ArticlefilesManager();
		article = rc.form(Article.class);
		if (article.getId() == -1)
			return false;
		List<String> paths = new ArrayList<String>();

		// 首先根据ID列出所有图片数据
		List<?> photos = photo.list(article.getId().intValue());
		for (Object aphoto : photos) {
			Articlephotos tmp = (Articlephotos) aphoto;
			paths.add(tmp.getFileserverpath());
			paths.add(tmp.getThumbpath());
		}
		// 首先根据ID列出所有附件数据
		List<?> files = file.list(article.getId().intValue());
		for (Object afile : files) {
			Articlefiles tmp = (Articlefiles) afile;
			paths.add(tmp.getFileserverpath());
		}

		// 采用事务删除数据，先删除图片及附件数据，后删除该文章信息
		String deletePhoto = "DELETE FROM articlephotos WHERE articleid=?";
		String deleteFiles = "DELETE FROM articlefiles WHERE articleid=?";
		String deleteArticle = "DELETE FROM article WHERE id=?";
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(deletePhoto, article.getId());
			QueryHelper.commitUpdate(deleteFiles, article.getId());
			QueryHelper.commitUpdate(deleteArticle, article.getId());
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				logger.error("删除文章时出现异常：{}", e1.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e1.getMessage());
			}
			logger.error("删除文章时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e.getMessage());
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				logger.error("删除文章时出现异常：{}", e2.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e2.getMessage());
			}
		}
		// 数据删除成功后删除硬盘上文件,无论文件是否存在，在删除时不返回任何异常
		if (flag) {
			for (String path : paths) {
				FileUtils.deleteQuietly(new File(RequestContext.root() + path));
			}
		}
		return true;
	}

}
